package com.ruibang.glass.quality.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author 宋锦康
 */
@Configuration
public class ExecutorConfig {

    /**
     * 项目共用线程池
     */
    public static final String SG_EXECUTOR = "shExecutor";

    @Bean
    @Primary
    public ThreadPoolTaskExecutor shExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 4);
        //队列大小
        threadPoolTaskExecutor.setQueueCapacity(1000);
        //线程池中线程名前缀
        threadPoolTaskExecutor.setThreadNamePrefix("quality-common-thread-pool-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
